// 模拟花卉数据
export const flowers = [
  {
    id: 1,
    name: '玫瑰',
    scientificName: 'Rosa',
    category: '观赏花卉',
    description: '玫瑰是世界上最受欢迎的花卉之一，象征着爱情和浪漫。它有多种颜色，每种颜色都有不同的象征意义。',
    image: 'https://picsum.photos/id/152/800/600',
    origin: '欧洲、亚洲、中东',
    floweringSeason: '春季至秋季',
    careTips: '需要充足的阳光，定期浇水但避免积水，保持良好的排水',
    price: 59.9,
    stock: 100,
    unit: '束',
    comments: [
      {
        id: 1,
        userId: 1,
        userName: '小明',
        content: '这朵玫瑰真漂亮！',
        createdAt: '2024-01-15T10:30:00Z'
      },
      {
        id: 2,
        userId: 2,
        userName: '小红',
        content: '我也很喜欢玫瑰，尤其是红色的。',
        createdAt: '2024-01-16T14:20:00Z'
      }
    ]
  },
  {
    id: 2,
    name: '郁金香',
    scientificName: 'Tulipa',
    category: '观赏花卉',
    description: '郁金香是荷兰的国花，以其优雅的形状和丰富的色彩而闻名。它是春季花园中最受欢迎的花卉之一。',
    image: 'https://picsum.photos/id/145/800/600',
    origin: '土耳其、中亚',
    floweringSeason: '春季',
    careTips: '喜欢凉爽的气候，需要充足的阳光和排水良好的土壤',
    price: 49.9,
    stock: 80,
    unit: '束',
    comments: [
      {
        id: 3,
        userId: 3,
        userName: '小花',
        content: '郁金香的颜色真多啊！',
        createdAt: '2024-01-10T09:15:00Z'
      }
    ]
  },
  {
    id: 3,
    name: '牡丹',
    scientificName: 'Paeonia',
    category: '观赏花卉',
    description: '牡丹被誉为"花中之王"，以其大而华丽的花朵和丰富的色彩而著称。在中国文化中，牡丹象征着富贵和吉祥。',
    image: 'https://picsum.photos/id/154/800/600',
    origin: '中国、日本、欧洲',
    floweringSeason: '春季至初夏',
    careTips: '喜欢阳光充足、温暖的环境，需要肥沃、排水良好的土壤',
    price: 89.9,
    stock: 50,
    unit: '束',
    comments: []
  },
  {
    id: 4,
    name: '向日葵',
    scientificName: 'Helianthus',
    category: '观赏花卉',
    description: '向日葵因其花盘会随着太阳转动而得名，象征着阳光、忠诚和长寿。它也是重要的经济作物。',
    image: 'https://picsum.photos/id/128/800/600',
    origin: '美洲',
    floweringSeason: '夏季至初秋',
    careTips: '需要充足的阳光和空间，耐旱但在生长期间需要定期浇水',
    price: 39.9,
    stock: 120,
    unit: '束',
    comments: [
      {
        id: 4,
        userId: 1,
        userName: '小明',
        content: '向日葵总是让人心情愉悦！',
        createdAt: '2024-01-18T16:45:00Z'
      }
    ]
  },
  {
    id: 5,
    name: '兰花',
    scientificName: 'Orchidaceae',
    category: '观赏花卉',
    description: '兰花是最大的植物科之一，以其独特的花形和浓郁的香气而闻名。它们在世界各地都有分布。',
    image: 'https://picsum.photos/id/118/800/600',
    origin: '全球热带和亚热带地区',
    floweringSeason: '因品种而异',
    careTips: '需要温暖、湿润的环境，适当的光照和通风，避免过度浇水',
    price: 129.9,
    stock: 30,
    unit: '盆',
    comments: []
  },
  {
    id: 6,
    name: '风信子',
    scientificName: 'Hyacinthus',
    category: '观赏花卉',
    description: '风信子是春季开花的球根植物，以其浓郁的香气和鲜艳的颜色而受欢迎。它们适合在花园和容器中种植。',
    image: 'https://picsum.photos/id/119/800/600',
    origin: '地中海沿岸',
    floweringSeason: '春季',
    careTips: '喜欢凉爽、湿润的环境，需要充足的阳光和排水良好的土壤',
    price: 45.9,
    stock: 60,
    unit: '盆',
    comments: []
  }
];

// 模拟用户数据
// 从localStorage获取用户数据，如果没有则使用默认数据
export let users = JSON.parse(localStorage.getItem('users')) || [
  {
    id: 1,
    username: 'admin',
    password: 'admin123',
    email: 'admin@example.com',
    role: 'admin'
  },
  {
    id: 2,
    username: 'user1',
    password: 'user123',
    email: 'user1@example.com',
    role: 'user'
  },
  {
    id: 3,
    username: 'user2',
    password: 'user456',
    email: 'user2@example.com',
    role: 'user'
  }
];

// 保存用户数据到localStorage
const saveUsersToLocalStorage = () => {
  localStorage.setItem('users', JSON.stringify(users));
};

// 模拟分类数据
export const categories = [
  { id: 1, name: '观赏花卉' },
  { id: 2, name: '药用花卉' },
  { id: 3, name: '食用花卉' },
  { id: 4, name: '野生花卉' },
  { id: 5, name: '室内花卉' }
];

// 登录验证函数（同时持久化登录状态）
export const login = (username, password) => {
  const user = users.find(u => u.username === username && u.password === password);
  if (user) {
    const { password, ...userWithoutPassword } = user;
    // 持久化到 localStorage，供导航栏与其他组件使用
    try {
      localStorage.setItem('user', JSON.stringify(userWithoutPassword));
      localStorage.setItem('isLoggedIn', 'true');
    } catch (e) {
      console.error('Failed to persist login state:', e);
    }
    return {
      success: true,
      user: userWithoutPassword
    };
  }
  return {
    success: false,
    message: '用户名或密码错误'
  };
};

// 注册函数
export const register = (username, password, email) => {
  // 检查用户名是否已存在
  const existingUser = users.find(u => u.username === username);
  if (existingUser) {
    return {
      success: false,
      message: '用户名已存在'
    };
  }
  
  // 检查邮箱是否已存在
  const existingEmail = users.find(u => u.email === email);
  if (existingEmail) {
    return {
      success: false,
      message: '邮箱已被注册'
    };
  }
  
  // 创建新用户
  const newUser = {
    id: Date.now(),
    username,
    password,
    email,
    role: 'user'
  };
  
  users.push(newUser);
  saveUsersToLocalStorage();
  
  const { password: _, ...userWithoutPassword } = newUser;
  return {
    success: true,
    user: userWithoutPassword
  };
};

// 获取当前登录用户
export const getCurrentUser = () => {
  const userStr = localStorage.getItem('user');
  return userStr ? JSON.parse(userStr) : null;
};

// 检查用户是否登录
export const isUserLoggedIn = () => {
  return localStorage.getItem('isLoggedIn') === 'true' && getCurrentUser() !== null;
};

// 获取花卉列表
export const getFlowers = () => {
  return flowers;
};

// ============= 购物车相关功能 =============

// 从localStorage获取购物车数据
const getCartFromLocalStorage = () => {
  try {
    const cart = localStorage.getItem('cart');
    return cart ? JSON.parse(cart) : [];
  } catch (error) {
    console.error('Failed to get cart from localStorage:', error);
    return [];
  }
};

// 保存购物车数据到localStorage
const saveCartToLocalStorage = (cart) => {
  try {
    localStorage.setItem('cart', JSON.stringify(cart));
  } catch (error) {
    console.error('Failed to save cart to localStorage:', error);
  }
};

// 添加商品到购物车
export const addToCart = (flowerId, quantity = 1) => {
  try {
    // 检查花卉是否存在
    const flower = getFlowerById(flowerId);
    if (!flower) {
      return { success: false, message: '花卉不存在' };
    }
    
    // 检查库存
    if (flower.stock < quantity) {
      return { success: false, message: '库存不足' };
    }
    
    // 获取购物车
    const cart = getCartFromLocalStorage();
    
    // 检查商品是否已在购物车中
    const existingItemIndex = cart.findIndex(item => item.id === flowerId);
    
    if (existingItemIndex >= 0) {
      // 更新已有商品的数量
      const newQuantity = cart[existingItemIndex].quantity + quantity;
      
      // 检查更新后的数量是否超过库存
      if (newQuantity > flower.stock) {
        return { success: false, message: '库存不足' };
      }
      
      cart[existingItemIndex].quantity = newQuantity;
    } else {
      // 添加新商品到购物车
      cart.push({
        id: flower.id,
        name: flower.name,
        price: flower.price,
        image: flower.image,
        unit: flower.unit,
        quantity: quantity
      });
    }
    
    // 保存购物车
    saveCartToLocalStorage(cart);
    
    return { success: true, message: '添加成功', cart };
  } catch (error) {
    console.error('Failed to add to cart:', error);
    return { success: false, message: '添加失败，请稍后重试' };
  }
};

// 从购物车移除商品
export const removeFromCart = (flowerId) => {
  try {
    const cart = getCartFromLocalStorage();
    const newCart = cart.filter(item => item.id !== flowerId);
    saveCartToLocalStorage(newCart);
    return { success: true, message: '移除成功', cart: newCart };
  } catch (error) {
    console.error('Failed to remove from cart:', error);
    return { success: false, message: '移除失败，请稍后重试' };
  }
};

// 更新购物车中商品的数量
export const updateCartItemQuantity = (flowerId, quantity) => {
  try {
    // 检查数量是否合法
    if (quantity <= 0) {
      return removeFromCart(flowerId);
    }
    
    // 检查花卉是否存在
    const flower = getFlowerById(flowerId);
    if (!flower) {
      return { success: false, message: '花卉不存在' };
    }
    
    // 检查库存
    if (flower.stock < quantity) {
      return { success: false, message: '库存不足' };
    }
    
    // 获取购物车
    const cart = getCartFromLocalStorage();
    
    // 查找并更新商品数量
    const itemIndex = cart.findIndex(item => item.id === flowerId);
    
    if (itemIndex >= 0) {
      cart[itemIndex].quantity = quantity;
      saveCartToLocalStorage(cart);
      return { success: true, message: '更新成功', cart };
    } else {
      return { success: false, message: '商品不在购物车中' };
    }
  } catch (error) {
    console.error('Failed to update cart item quantity:', error);
    return { success: false, message: '更新失败，请稍后重试' };
  }
};

// 获取购物车中的所有商品
export const getCartItems = () => {
  try {
    return getCartFromLocalStorage();
  } catch (error) {
    console.error('Failed to get cart items:', error);
    return [];
  }
};

// 清空购物车
export const clearCart = () => {
  try {
    localStorage.removeItem('cart');
    return { success: true, message: '购物车已清空' };
  } catch (error) {
    console.error('Failed to clear cart:', error);
    return { success: false, message: '清空失败，请稍后重试' };
  }
};

// 获取购物车中的商品总数
export const getCartItemCount = () => {
  try {
    const cart = getCartFromLocalStorage();
    return cart.reduce((total, item) => total + item.quantity, 0);
  } catch (error) {
    console.error('Failed to get cart item count:', error);
    return 0;
  }
};

// 获取购物车总价
export const getCartTotalPrice = () => {
  try {
    const cart = getCartFromLocalStorage();
    return cart.reduce((total, item) => total + (item.price * item.quantity), 0);
  } catch (error) {
    console.error('Failed to get cart total price:', error);
    return 0;
  }
};

// 获取单个花卉详情
export const getFlowerById = (id) => {
  return flowers.find(flower => flower.id === parseInt(id));
};

// 添加评论
export const addComment = (flowerId, comment) => {
  const flower = getFlowerById(flowerId);
  if (flower) {
    const newComment = {
      id: Date.now(),
      ...comment,
      createdAt: new Date().toISOString()
    };
    flower.comments.push(newComment);
    return {
      success: true,
      comment: newComment
    };
  }
  return {
    success: false,
    message: '花卉不存在'
  };
};

// 获取花卉分类
export const getCategories = () => {
  return categories;
};

// 根据分类获取花卉
export const getFlowersByCategory = (category) => {
  return flowers.filter(flower => flower.category === category);
};
/**
 * 数据与业务服务：
 * - 模拟用户数据与登录/注册逻辑（通过 localStorage 持久化）
 * - 提供花卉与分类数据
 * - 购物车工具函数（计数、添加、移除等）
 * 导出方法示例：
 * - login, register, isUserLoggedIn, getCurrentUser
 * - getFlowers, getCategories
 * - addToCart, removeFromCart, getCartItemCount
 */